/** 
 * @CopyRight (c) 2012-2012
 * @Project <jtao>
 * @JDK_Version_Used:<JDK1.6>
 * @Description:<描述用途>
 * @Title: BuyTools.java
 * @Author: <何俊>
 * @Author_of_Contact <E:azj1001@sina.com T:18651831939>
 * @Date 2012-11-10 下午3:04:40
 * @Modified_By: <修改人>
 * @Modified_of_Contact <修改人联系方式>
 * @Modified_Date <修改日期时间>
 * @Why & What is modified <修改原因描述>
 * @Version v1.00
 */
package com.e.buy;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import cn.commons.ICommons;
import cn.commons.dbclient.exception.AzjDbClientException;
import cn.commons.query.ConditionBean;
import cn.commons.query.exception.AzjQueryBuilderException;

import com.e.buy.bean.SqlRegister;
import com.e.buy.enums.Status;
import com.e.buy.tools.ToolsBox;
import com.e.buy.tools.WebPropertiesTools;

/**
 * @Description:(描述类别作用)
 * @author <何俊>
 * @date 2012-11-10 下午3:04:40
 * @version v1.0
 * @Other :@see #Files
 */
public class BuyTools {

	protected final Logger log4j = Logger.getLogger(getClass());

	protected WebPropertiesTools webProperties = null;

	protected ToolsBox toolsbox = null;

	protected SqlRegister register = null;

	@Resource
	protected ICommons service = null;

	public BuyTools() {
		try {
			toolsbox = ToolsBox.getInstance();
			this.webProperties = WebPropertiesTools.getInstance();
		} catch (AzjDbClientException e) {
			log4j.error("Load Commons WebProperties Tools Error");
		}
	}

	protected String getWebProperties(String mkey, String vkey) {
		try {
			return webProperties.getPropertiesVal(mkey, vkey);
		} catch (AzjDbClientException e) {
			log4j.error(e);
		}
		return "";
	}

	/**
	 * @Description:<获取访问者的IP>
	 * @title: getVisitorIp
	 * @param req
	 * @return String 返回类型
	 * @throws
	 */
	protected String getVisitorIp(HttpServletRequest req) {
		if (req.getHeader("x-forwarded-for") == null) {
			return req.getRemoteAddr();
		}
		String ip = req.getHeader("x-forwarded-for");
		// 多层反向代理，取第一个ip
		if (ip.split(",").length > 1) {
			ip = ip.split(",")[0];
		}
		return ip;
	}

	/**
	 * @Description:<字符串是否为空>
	 * @title: isEmptyStr
	 * @param str
	 * @return boolean 返回类型
	 * @throws
	 */
	protected boolean isEmptyStr(String str) {
		return (null == str || str.trim().length() == 0);
	}
	
	/**
	 * @Description:<写上传文件到本地磁盘>
	 * @title: writUploadPic
	 * @param in
	 * @param savePath
	 * @return boolean 返回类型
	 * @throws
	 */
	protected boolean writUploadPic(InputStream in,String savePath) {
		boolean b = true;
		OutputStream out = null;
		try {
			if(in.available() > 0) {
				byte[] bt = new byte[in.available()];
				File f = new File(savePath);
				f.deleteOnExit();
				File dir = new File(f.getParent());
				dir.mkdirs();
				f.createNewFile();
				out = new FileOutputStream(f);
				int len = in.read(bt);
				if(len > 0) {
					out.write(bt);
				}
			}
		} catch (Exception e) {
			log4j.error("Writ File Error:" + e);
			b = false;
		} finally {
			try{
				in.close();
				out.close();
			} catch (Exception e) {
				in = null;
				out = null;
			}
		}
		return b;
	}
	
	/**
	 * @Description:<获取查询操作的sql子程序实现>
	 * @title: getEnumSql
	 * @param e
	 * @param state
	 * @return String 返回类型
	 * @throws
	 */
	public String getEnumSql(Enum<?> e, Status state) {
		return null;
	}

	public void setService(ICommons service) {
		this.service = service;
	}

	/**
	 * @Description:<查询对象>
	 * @title: queryForObject
	 * @param e
	 * @param state
	 * @param c
	 * @param beans
	 * @param args
	 * @return Object 返回类型
	 * @throws AzjQueryBuilderException
	 */
	public Object queryForObject(Enum<?> e, Status state, Class<?> c, List<ConditionBean> beans, Object... args)
			throws AzjQueryBuilderException {
		String sql = this.getEnumSql(e, state);
		return service.queryForObject(sql, c, beans, args);
	}

	/**
	 * @Description:<查询集合>
	 * @title: querForList
	 * @param e
	 * @param state
	 * @param c
	 * @param beans
	 * @param args
	 * @return List<?> 返回类型
	 * @throws AzjQueryBuilderException
	 */
	public List<?> querForList(Enum<?> e, Status state, Class<?> c, List<ConditionBean> beans, Object... args)
			throws AzjQueryBuilderException {
		String sql = this.getEnumSql(e, state);
		return service.queryForList(sql, c, beans, args);
	}

	/**
	 * 
	 * @Description:<指定排序列的分页查询集合>
	 * @title: queryPagin
	 * @param pageSize
	 * @param pageNumber
	 * @param c
	 * @param e
	 * @param sortable :是否加载后台排序字段
	 * @param sortcol : 排序列
	 * @param desc : 是否倒序
	 * @param beans
	 * @param args
	 * @throws AzjQueryBuilderException
	 * @return List<?> 返回类型
	 * @throws
	 */
	public List<?> queryPagin(int pageSize, int pageNumber, Class<?> c, Enum<?> e, boolean sortable, String sortcol,
			boolean desc, List<ConditionBean> beans, Object... args) throws AzjQueryBuilderException {
		// 排序
		String odr = " ORDER BY ";
		String sort = "";
		if (sortcol != null && sortcol.trim().length() > 0) {
			sort = sortable ? this.getEnumSql(e, Status.SORT) + "," + sortcol : sortcol;
		} else {
			sort = sortable ? this.getEnumSql(e, Status.SORT) : "";
		}
		if (!sort.equals("")) {
			sort = odr + (desc ? sort + " DESC" : sort + " ASC");
		}

		// 参数
		String pagin = this.getEnumSql(e, Status.PAGIN);
		String head = this.getEnumSql(e, Status.HEAD);
		String qy = this.service.buliderCondition(beans);
		Object[] params = this.service.unionConditionBeanArgs(beans, args);
		// SQL
		StringBuilder sql = new StringBuilder();
		sql.append(head + " FROM (");
		sql.append(pagin + qy + sort);
		sql.append(" LIMIT " + ((pageNumber-1) * pageSize) + "," + pageSize);
		sql.append(" ) t LIMIT " + pageSize);
		// 操作
		return service.queryForList(sql.toString(), c, params);
	}
}
